/**
 * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package com.mad.bikepony.service.persistence;

import com.liferay.portal.NoSuchModelException;
import com.liferay.portal.kernel.bean.BeanReference;
import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ArrayUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.BatchSessionUtil;
import com.liferay.portal.service.persistence.ResourcePersistence;
import com.liferay.portal.service.persistence.UserPersistence;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

import com.mad.bikepony.NoSuchDeliveryException;
import com.mad.bikepony.model.Delivery;
import com.mad.bikepony.model.impl.DeliveryImpl;
import com.mad.bikepony.model.impl.DeliveryModelImpl;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * The persistence implementation for the delivery service.
 *
 * <p>
 * Caching information and settings can be found in <code>portal.properties</code>
 * </p>
 *
 * @author nicola
 * @see DeliveryPersistence
 * @see DeliveryUtil
 * @generated
 */
public class DeliveryPersistenceImpl extends BasePersistenceImpl<Delivery>
	implements DeliveryPersistence {
	/*
	 * NOTE FOR DEVELOPERS:
	 *
	 * Never modify or reference this class directly. Always use {@link DeliveryUtil} to access the delivery persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
	 */
	public static final String FINDER_CLASS_NAME_ENTITY = DeliveryImpl.class.getName();
	public static final String FINDER_CLASS_NAME_LIST_WITH_PAGINATION = FINDER_CLASS_NAME_ENTITY +
		".List1";
	public static final String FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION = FINDER_CLASS_NAME_ENTITY +
		".List2";
	public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_DELIVERYSTATEANDAGENTID =
		new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, DeliveryImpl.class,
			FINDER_CLASS_NAME_LIST_WITH_PAGINATION,
			"findByDeliveryStateAndAgentId",
			new String[] {
				Long.class.getName(), Integer.class.getName(),
				
			"java.lang.Integer", "java.lang.Integer",
				"com.liferay.portal.kernel.util.OrderByComparator"
			});
	public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DELIVERYSTATEANDAGENTID =
		new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, DeliveryImpl.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION,
			"findByDeliveryStateAndAgentId",
			new String[] { Long.class.getName(), Integer.class.getName() },
			DeliveryModelImpl.AGENTID_COLUMN_BITMASK |
			DeliveryModelImpl.STATE_COLUMN_BITMASK);
	public static final FinderPath FINDER_PATH_COUNT_BY_DELIVERYSTATEANDAGENTID = new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION,
			"countByDeliveryStateAndAgentId",
			new String[] { Long.class.getName(), Integer.class.getName() });
	public static final FinderPath FINDER_PATH_WITH_PAGINATION_COUNT_BY_DELIVERYSTATEANDAGENTID =
		new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITH_PAGINATION,
			"countByDeliveryStateAndAgentId",
			new String[] { Long.class.getName(), Integer.class.getName() });
	public static final FinderPath FINDER_PATH_FETCH_BY_DELIVERYIDANDAGENTID = new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, DeliveryImpl.class,
			FINDER_CLASS_NAME_ENTITY, "fetchByDeliveryIdAndAgentId",
			new String[] { Long.class.getName(), Long.class.getName() },
			DeliveryModelImpl.DELIVERYID_COLUMN_BITMASK |
			DeliveryModelImpl.AGENTID_COLUMN_BITMASK);
	public static final FinderPath FINDER_PATH_COUNT_BY_DELIVERYIDANDAGENTID = new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION,
			"countByDeliveryIdAndAgentId",
			new String[] { Long.class.getName(), Long.class.getName() });
	public static final FinderPath FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID =
		new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, DeliveryImpl.class,
			FINDER_CLASS_NAME_ENTITY,
			"fetchByDeliveryIdAndDeliveryStateAndAgentId",
			new String[] {
				Long.class.getName(), Long.class.getName(),
				Integer.class.getName()
			},
			DeliveryModelImpl.DELIVERYID_COLUMN_BITMASK |
			DeliveryModelImpl.AGENTID_COLUMN_BITMASK |
			DeliveryModelImpl.STATE_COLUMN_BITMASK);
	public static final FinderPath FINDER_PATH_COUNT_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID =
		new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION,
			"countByDeliveryIdAndDeliveryStateAndAgentId",
			new String[] {
				Long.class.getName(), Long.class.getName(),
				Integer.class.getName()
			});
	public static final FinderPath FINDER_PATH_WITH_PAGINATION_COUNT_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID =
		new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITH_PAGINATION,
			"countByDeliveryIdAndDeliveryStateAndAgentId",
			new String[] {
				Long.class.getName(), Long.class.getName(),
				Integer.class.getName()
			});
	public static final FinderPath FINDER_PATH_FETCH_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID =
		new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, DeliveryImpl.class,
			FINDER_CLASS_NAME_ENTITY,
			"fetchByDeliveryIdAndTrackingCodeAndAgentId",
			new String[] {
				Long.class.getName(), String.class.getName(),
				Long.class.getName()
			},
			DeliveryModelImpl.DELIVERYID_COLUMN_BITMASK |
			DeliveryModelImpl.TRACKINGCODE_COLUMN_BITMASK |
			DeliveryModelImpl.AGENTID_COLUMN_BITMASK);
	public static final FinderPath FINDER_PATH_COUNT_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID =
		new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION,
			"countByDeliveryIdAndTrackingCodeAndAgentId",
			new String[] {
				Long.class.getName(), String.class.getName(),
				Long.class.getName()
			});
	public static final FinderPath FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID =
		new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, DeliveryImpl.class,
			FINDER_CLASS_NAME_ENTITY,
			"fetchByDeliveryIdAndDeliveryCodeAndAgentId",
			new String[] {
				Long.class.getName(), String.class.getName(),
				Long.class.getName()
			},
			DeliveryModelImpl.DELIVERYID_COLUMN_BITMASK |
			DeliveryModelImpl.DELIVERYCODE_COLUMN_BITMASK |
			DeliveryModelImpl.AGENTID_COLUMN_BITMASK);
	public static final FinderPath FINDER_PATH_COUNT_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID =
		new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION,
			"countByDeliveryIdAndDeliveryCodeAndAgentId",
			new String[] {
				Long.class.getName(), String.class.getName(),
				Long.class.getName()
			});
	public static final FinderPath FINDER_PATH_FETCH_BY_TRACKINGCODE = new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, DeliveryImpl.class,
			FINDER_CLASS_NAME_ENTITY, "fetchByTrackingCode",
			new String[] { String.class.getName() },
			DeliveryModelImpl.TRACKINGCODE_COLUMN_BITMASK);
	public static final FinderPath FINDER_PATH_COUNT_BY_TRACKINGCODE = new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByTrackingCode",
			new String[] { String.class.getName() });
	public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_ALL = new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, DeliveryImpl.class,
			FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findAll", new String[0]);
	public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL = new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, DeliveryImpl.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findAll", new String[0]);
	public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countAll", new String[0]);

	/**
	 * Caches the delivery in the entity cache if it is enabled.
	 *
	 * @param delivery the delivery
	 */
	public void cacheResult(Delivery delivery) {
		EntityCacheUtil.putResult(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryImpl.class, delivery.getPrimaryKey(), delivery);

		FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDAGENTID,
			new Object[] {
				Long.valueOf(delivery.getDeliveryId()),
				Long.valueOf(delivery.getAgentId())
			}, delivery);

		FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
			new Object[] {
				Long.valueOf(delivery.getDeliveryId()),
				Long.valueOf(delivery.getAgentId()),
				Integer.valueOf(delivery.getState())
			}, delivery);

		FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
			new Object[] {
				Long.valueOf(delivery.getDeliveryId()),
				
			delivery.getTrackingCode(), Long.valueOf(delivery.getAgentId())
			}, delivery);

		FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
			new Object[] {
				Long.valueOf(delivery.getDeliveryId()),
				
			delivery.getDeliveryCode(), Long.valueOf(delivery.getAgentId())
			}, delivery);

		FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_TRACKINGCODE,
			new Object[] { delivery.getTrackingCode() }, delivery);

		delivery.resetOriginalValues();
	}

	/**
	 * Caches the deliveries in the entity cache if it is enabled.
	 *
	 * @param deliveries the deliveries
	 */
	public void cacheResult(List<Delivery> deliveries) {
		for (Delivery delivery : deliveries) {
			if (EntityCacheUtil.getResult(
						DeliveryModelImpl.ENTITY_CACHE_ENABLED,
						DeliveryImpl.class, delivery.getPrimaryKey()) == null) {
				cacheResult(delivery);
			}
			else {
				delivery.resetOriginalValues();
			}
		}
	}

	/**
	 * Clears the cache for all deliveries.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	@Override
	public void clearCache() {
		if (_HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE) {
			CacheRegistryUtil.clear(DeliveryImpl.class.getName());
		}

		EntityCacheUtil.clearCache(DeliveryImpl.class.getName());

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
	}

	/**
	 * Clears the cache for the delivery.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	@Override
	public void clearCache(Delivery delivery) {
		EntityCacheUtil.removeResult(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryImpl.class, delivery.getPrimaryKey());

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);

		clearUniqueFindersCache(delivery);
	}

	@Override
	public void clearCache(List<Delivery> deliveries) {
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);

		for (Delivery delivery : deliveries) {
			EntityCacheUtil.removeResult(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
				DeliveryImpl.class, delivery.getPrimaryKey());

			clearUniqueFindersCache(delivery);
		}
	}

	protected void clearUniqueFindersCache(Delivery delivery) {
		FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDAGENTID,
			new Object[] {
				Long.valueOf(delivery.getDeliveryId()),
				Long.valueOf(delivery.getAgentId())
			});

		FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
			new Object[] {
				Long.valueOf(delivery.getDeliveryId()),
				Long.valueOf(delivery.getAgentId()),
				Integer.valueOf(delivery.getState())
			});

		FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
			new Object[] {
				Long.valueOf(delivery.getDeliveryId()),
				
			delivery.getTrackingCode(), Long.valueOf(delivery.getAgentId())
			});

		FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
			new Object[] {
				Long.valueOf(delivery.getDeliveryId()),
				
			delivery.getDeliveryCode(), Long.valueOf(delivery.getAgentId())
			});

		FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_TRACKINGCODE,
			new Object[] { delivery.getTrackingCode() });
	}

	/**
	 * Creates a new delivery with the primary key. Does not add the delivery to the database.
	 *
	 * @param deliveryId the primary key for the new delivery
	 * @return the new delivery
	 */
	public Delivery create(long deliveryId) {
		Delivery delivery = new DeliveryImpl();

		delivery.setNew(true);
		delivery.setPrimaryKey(deliveryId);

		return delivery;
	}

	/**
	 * Removes the delivery with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param deliveryId the primary key of the delivery
	 * @return the delivery that was removed
	 * @throws com.mad.bikepony.NoSuchDeliveryException if a delivery with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery remove(long deliveryId)
		throws NoSuchDeliveryException, SystemException {
		return remove(Long.valueOf(deliveryId));
	}

	/**
	 * Removes the delivery with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param primaryKey the primary key of the delivery
	 * @return the delivery that was removed
	 * @throws com.mad.bikepony.NoSuchDeliveryException if a delivery with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Delivery remove(Serializable primaryKey)
		throws NoSuchDeliveryException, SystemException {
		Session session = null;

		try {
			session = openSession();

			Delivery delivery = (Delivery)session.get(DeliveryImpl.class,
					primaryKey);

			if (delivery == null) {
				if (_log.isWarnEnabled()) {
					_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
				}

				throw new NoSuchDeliveryException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
					primaryKey);
			}

			return remove(delivery);
		}
		catch (NoSuchDeliveryException nsee) {
			throw nsee;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	@Override
	protected Delivery removeImpl(Delivery delivery) throws SystemException {
		delivery = toUnwrappedModel(delivery);

		Session session = null;

		try {
			session = openSession();

			BatchSessionUtil.delete(session, delivery);
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		clearCache(delivery);

		return delivery;
	}

	@Override
	public Delivery updateImpl(com.mad.bikepony.model.Delivery delivery,
		boolean merge) throws SystemException {
		delivery = toUnwrappedModel(delivery);

		boolean isNew = delivery.isNew();

		DeliveryModelImpl deliveryModelImpl = (DeliveryModelImpl)delivery;

		Session session = null;

		try {
			session = openSession();

			BatchSessionUtil.update(session, delivery, merge);

			delivery.setNew(false);
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);

		if (isNew || !DeliveryModelImpl.COLUMN_BITMASK_ENABLED) {
			FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
		}

		else {
			if ((deliveryModelImpl.getColumnBitmask() &
					FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DELIVERYSTATEANDAGENTID.getColumnBitmask()) != 0) {
				Object[] args = new Object[] {
						Long.valueOf(deliveryModelImpl.getOriginalAgentId()),
						Integer.valueOf(deliveryModelImpl.getOriginalState())
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DELIVERYSTATEANDAGENTID,
					args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DELIVERYSTATEANDAGENTID,
					args);

				args = new Object[] {
						Long.valueOf(deliveryModelImpl.getAgentId()),
						Integer.valueOf(deliveryModelImpl.getState())
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DELIVERYSTATEANDAGENTID,
					args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DELIVERYSTATEANDAGENTID,
					args);
			}
		}

		EntityCacheUtil.putResult(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
			DeliveryImpl.class, delivery.getPrimaryKey(), delivery);

		if (isNew) {
			FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDAGENTID,
				new Object[] {
					Long.valueOf(delivery.getDeliveryId()),
					Long.valueOf(delivery.getAgentId())
				}, delivery);

			FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
				new Object[] {
					Long.valueOf(delivery.getDeliveryId()),
					Long.valueOf(delivery.getAgentId()),
					Integer.valueOf(delivery.getState())
				}, delivery);

			FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
				new Object[] {
					Long.valueOf(delivery.getDeliveryId()),
					
				delivery.getTrackingCode(), Long.valueOf(delivery.getAgentId())
				}, delivery);

			FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
				new Object[] {
					Long.valueOf(delivery.getDeliveryId()),
					
				delivery.getDeliveryCode(), Long.valueOf(delivery.getAgentId())
				}, delivery);

			FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_TRACKINGCODE,
				new Object[] { delivery.getTrackingCode() }, delivery);
		}
		else {
			if ((deliveryModelImpl.getColumnBitmask() &
					FINDER_PATH_FETCH_BY_DELIVERYIDANDAGENTID.getColumnBitmask()) != 0) {
				Object[] args = new Object[] {
						Long.valueOf(deliveryModelImpl.getOriginalDeliveryId()),
						Long.valueOf(deliveryModelImpl.getOriginalAgentId())
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDAGENTID,
					args);

				FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDAGENTID,
					args);

				FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDAGENTID,
					new Object[] {
						Long.valueOf(delivery.getDeliveryId()),
						Long.valueOf(delivery.getAgentId())
					}, delivery);
			}

			if ((deliveryModelImpl.getColumnBitmask() &
					FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID.getColumnBitmask()) != 0) {
				Object[] args = new Object[] {
						Long.valueOf(deliveryModelImpl.getOriginalDeliveryId()),
						Long.valueOf(deliveryModelImpl.getOriginalAgentId()),
						Integer.valueOf(deliveryModelImpl.getOriginalState())
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
					args);

				FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
					args);

				FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
					new Object[] {
						Long.valueOf(delivery.getDeliveryId()),
						Long.valueOf(delivery.getAgentId()),
						Integer.valueOf(delivery.getState())
					}, delivery);
			}

			if ((deliveryModelImpl.getColumnBitmask() &
					FINDER_PATH_FETCH_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID.getColumnBitmask()) != 0) {
				Object[] args = new Object[] {
						Long.valueOf(deliveryModelImpl.getOriginalDeliveryId()),
						
						deliveryModelImpl.getOriginalTrackingCode(),
						Long.valueOf(deliveryModelImpl.getOriginalAgentId())
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
					args);

				FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
					args);

				FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
					new Object[] {
						Long.valueOf(delivery.getDeliveryId()),
						
					delivery.getTrackingCode(),
						Long.valueOf(delivery.getAgentId())
					}, delivery);
			}

			if ((deliveryModelImpl.getColumnBitmask() &
					FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID.getColumnBitmask()) != 0) {
				Object[] args = new Object[] {
						Long.valueOf(deliveryModelImpl.getOriginalDeliveryId()),
						
						deliveryModelImpl.getOriginalDeliveryCode(),
						Long.valueOf(deliveryModelImpl.getOriginalAgentId())
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
					args);

				FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
					args);

				FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
					new Object[] {
						Long.valueOf(delivery.getDeliveryId()),
						
					delivery.getDeliveryCode(),
						Long.valueOf(delivery.getAgentId())
					}, delivery);
			}

			if ((deliveryModelImpl.getColumnBitmask() &
					FINDER_PATH_FETCH_BY_TRACKINGCODE.getColumnBitmask()) != 0) {
				Object[] args = new Object[] {
						deliveryModelImpl.getOriginalTrackingCode()
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_TRACKINGCODE,
					args);

				FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_TRACKINGCODE,
					args);

				FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_TRACKINGCODE,
					new Object[] { delivery.getTrackingCode() }, delivery);
			}
		}

		return delivery;
	}

	protected Delivery toUnwrappedModel(Delivery delivery) {
		if (delivery instanceof DeliveryImpl) {
			return delivery;
		}

		DeliveryImpl deliveryImpl = new DeliveryImpl();

		deliveryImpl.setNew(delivery.isNew());
		deliveryImpl.setPrimaryKey(delivery.getPrimaryKey());

		deliveryImpl.setDeliveryId(delivery.getDeliveryId());
		deliveryImpl.setDeliveryCode(delivery.getDeliveryCode());
		deliveryImpl.setTrackingCode(delivery.getTrackingCode());
		deliveryImpl.setSenderAddress(delivery.getSenderAddress());
		deliveryImpl.setSenderAdditionalInfo(delivery.getSenderAdditionalInfo());
		deliveryImpl.setSenderEmail(delivery.getSenderEmail());
		deliveryImpl.setRecipientAddress(delivery.getRecipientAddress());
		deliveryImpl.setRecipientAdditionalInfo(delivery.getRecipientAdditionalInfo());
		deliveryImpl.setRecipientEmail(delivery.getRecipientEmail());
		deliveryImpl.setState(delivery.getState());
		deliveryImpl.setAgentId(delivery.getAgentId());
		deliveryImpl.setSubmissionTimestamp(delivery.getSubmissionTimestamp());
		deliveryImpl.setPickupTimestamp(delivery.getPickupTimestamp());
		deliveryImpl.setDeliveryTimestamp(delivery.getDeliveryTimestamp());
		deliveryImpl.setRecipientSignature(delivery.getRecipientSignature());
		deliveryImpl.setEstimatedPickupTime(delivery.getEstimatedPickupTime());
		deliveryImpl.setEstimatedDeliveryTime(delivery.getEstimatedDeliveryTime());

		return deliveryImpl;
	}

	/**
	 * Returns the delivery with the primary key or throws a {@link com.liferay.portal.NoSuchModelException} if it could not be found.
	 *
	 * @param primaryKey the primary key of the delivery
	 * @return the delivery
	 * @throws com.liferay.portal.NoSuchModelException if a delivery with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Delivery findByPrimaryKey(Serializable primaryKey)
		throws NoSuchModelException, SystemException {
		return findByPrimaryKey(((Long)primaryKey).longValue());
	}

	/**
	 * Returns the delivery with the primary key or throws a {@link com.mad.bikepony.NoSuchDeliveryException} if it could not be found.
	 *
	 * @param deliveryId the primary key of the delivery
	 * @return the delivery
	 * @throws com.mad.bikepony.NoSuchDeliveryException if a delivery with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery findByPrimaryKey(long deliveryId)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = fetchByPrimaryKey(deliveryId);

		if (delivery == null) {
			if (_log.isWarnEnabled()) {
				_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + deliveryId);
			}

			throw new NoSuchDeliveryException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
				deliveryId);
		}

		return delivery;
	}

	/**
	 * Returns the delivery with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param primaryKey the primary key of the delivery
	 * @return the delivery, or <code>null</code> if a delivery with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Delivery fetchByPrimaryKey(Serializable primaryKey)
		throws SystemException {
		return fetchByPrimaryKey(((Long)primaryKey).longValue());
	}

	/**
	 * Returns the delivery with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param deliveryId the primary key of the delivery
	 * @return the delivery, or <code>null</code> if a delivery with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByPrimaryKey(long deliveryId)
		throws SystemException {
		Delivery delivery = (Delivery)EntityCacheUtil.getResult(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
				DeliveryImpl.class, deliveryId);

		if (delivery == _nullDelivery) {
			return null;
		}

		if (delivery == null) {
			Session session = null;

			boolean hasException = false;

			try {
				session = openSession();

				delivery = (Delivery)session.get(DeliveryImpl.class,
						Long.valueOf(deliveryId));
			}
			catch (Exception e) {
				hasException = true;

				throw processException(e);
			}
			finally {
				if (delivery != null) {
					cacheResult(delivery);
				}
				else if (!hasException) {
					EntityCacheUtil.putResult(DeliveryModelImpl.ENTITY_CACHE_ENABLED,
						DeliveryImpl.class, deliveryId, _nullDelivery);
				}

				closeSession(session);
			}
		}

		return delivery;
	}

	/**
	 * Returns all the deliveries where agentId = &#63; and state = &#63;.
	 *
	 * @param agentId the agent ID
	 * @param state the state
	 * @return the matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public List<Delivery> findByDeliveryStateAndAgentId(long agentId, int state)
		throws SystemException {
		return findByDeliveryStateAndAgentId(agentId, state, QueryUtil.ALL_POS,
			QueryUtil.ALL_POS, null);
	}

	/**
	 * Returns a range of all the deliveries where agentId = &#63; and state = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param agentId the agent ID
	 * @param state the state
	 * @param start the lower bound of the range of deliveries
	 * @param end the upper bound of the range of deliveries (not inclusive)
	 * @return the range of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public List<Delivery> findByDeliveryStateAndAgentId(long agentId,
		int state, int start, int end) throws SystemException {
		return findByDeliveryStateAndAgentId(agentId, state, start, end, null);
	}

	/**
	 * Returns an ordered range of all the deliveries where agentId = &#63; and state = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param agentId the agent ID
	 * @param state the state
	 * @param start the lower bound of the range of deliveries
	 * @param end the upper bound of the range of deliveries (not inclusive)
	 * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
	 * @return the ordered range of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public List<Delivery> findByDeliveryStateAndAgentId(long agentId,
		int state, int start, int end, OrderByComparator orderByComparator)
		throws SystemException {
		FinderPath finderPath = null;
		Object[] finderArgs = null;

		if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
				(orderByComparator == null)) {
			finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DELIVERYSTATEANDAGENTID;
			finderArgs = new Object[] { agentId, state };
		}
		else {
			finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_DELIVERYSTATEANDAGENTID;
			finderArgs = new Object[] {
					agentId, state,
					
					start, end, orderByComparator
				};
		}

		List<Delivery> list = (List<Delivery>)FinderCacheUtil.getResult(finderPath,
				finderArgs, this);

		if ((list != null) && !list.isEmpty()) {
			for (Delivery delivery : list) {
				if ((agentId != delivery.getAgentId()) ||
						(state != delivery.getState())) {
					list = null;

					break;
				}
			}
		}

		if (list == null) {
			StringBundler query = null;

			if (orderByComparator != null) {
				query = new StringBundler(4 +
						(orderByComparator.getOrderByFields().length * 3));
			}
			else {
				query = new StringBundler(3);
			}

			query.append(_SQL_SELECT_DELIVERY_WHERE);

			query.append(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_AGENTID_2);

			query.append(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_STATE_2);

			if (orderByComparator != null) {
				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(agentId);

				qPos.add(state);

				list = (List<Delivery>)QueryUtil.list(q, getDialect(), start,
						end);
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (list == null) {
					FinderCacheUtil.removeResult(finderPath, finderArgs);
				}
				else {
					cacheResult(list);

					FinderCacheUtil.putResult(finderPath, finderArgs, list);
				}

				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Returns the first delivery in the ordered set where agentId = &#63; and state = &#63;.
	 *
	 * @param agentId the agent ID
	 * @param state the state
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching delivery
	 * @throws com.mad.bikepony.NoSuchDeliveryException if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery findByDeliveryStateAndAgentId_First(long agentId,
		int state, OrderByComparator orderByComparator)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = fetchByDeliveryStateAndAgentId_First(agentId,
				state, orderByComparator);

		if (delivery != null) {
			return delivery;
		}

		StringBundler msg = new StringBundler(6);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("agentId=");
		msg.append(agentId);

		msg.append(", state=");
		msg.append(state);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchDeliveryException(msg.toString());
	}

	/**
	 * Returns the first delivery in the ordered set where agentId = &#63; and state = &#63;.
	 *
	 * @param agentId the agent ID
	 * @param state the state
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByDeliveryStateAndAgentId_First(long agentId,
		int state, OrderByComparator orderByComparator)
		throws SystemException {
		List<Delivery> list = findByDeliveryStateAndAgentId(agentId, state, 0,
				1, orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the last delivery in the ordered set where agentId = &#63; and state = &#63;.
	 *
	 * @param agentId the agent ID
	 * @param state the state
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching delivery
	 * @throws com.mad.bikepony.NoSuchDeliveryException if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery findByDeliveryStateAndAgentId_Last(long agentId, int state,
		OrderByComparator orderByComparator)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = fetchByDeliveryStateAndAgentId_Last(agentId, state,
				orderByComparator);

		if (delivery != null) {
			return delivery;
		}

		StringBundler msg = new StringBundler(6);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("agentId=");
		msg.append(agentId);

		msg.append(", state=");
		msg.append(state);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchDeliveryException(msg.toString());
	}

	/**
	 * Returns the last delivery in the ordered set where agentId = &#63; and state = &#63;.
	 *
	 * @param agentId the agent ID
	 * @param state the state
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByDeliveryStateAndAgentId_Last(long agentId,
		int state, OrderByComparator orderByComparator)
		throws SystemException {
		int count = countByDeliveryStateAndAgentId(agentId, state);

		List<Delivery> list = findByDeliveryStateAndAgentId(agentId, state,
				count - 1, count, orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the deliveries before and after the current delivery in the ordered set where agentId = &#63; and state = &#63;.
	 *
	 * @param deliveryId the primary key of the current delivery
	 * @param agentId the agent ID
	 * @param state the state
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the previous, current, and next delivery
	 * @throws com.mad.bikepony.NoSuchDeliveryException if a delivery with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery[] findByDeliveryStateAndAgentId_PrevAndNext(
		long deliveryId, long agentId, int state,
		OrderByComparator orderByComparator)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = findByPrimaryKey(deliveryId);

		Session session = null;

		try {
			session = openSession();

			Delivery[] array = new DeliveryImpl[3];

			array[0] = getByDeliveryStateAndAgentId_PrevAndNext(session,
					delivery, agentId, state, orderByComparator, true);

			array[1] = delivery;

			array[2] = getByDeliveryStateAndAgentId_PrevAndNext(session,
					delivery, agentId, state, orderByComparator, false);

			return array;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected Delivery getByDeliveryStateAndAgentId_PrevAndNext(
		Session session, Delivery delivery, long agentId, int state,
		OrderByComparator orderByComparator, boolean previous) {
		StringBundler query = null;

		if (orderByComparator != null) {
			query = new StringBundler(6 +
					(orderByComparator.getOrderByFields().length * 6));
		}
		else {
			query = new StringBundler(3);
		}

		query.append(_SQL_SELECT_DELIVERY_WHERE);

		query.append(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_AGENTID_2);

		query.append(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_STATE_2);

		if (orderByComparator != null) {
			String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();

			if (orderByConditionFields.length > 0) {
				query.append(WHERE_AND);
			}

			for (int i = 0; i < orderByConditionFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByConditionFields[i]);

				if ((i + 1) < orderByConditionFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN_HAS_NEXT);
					}
					else {
						query.append(WHERE_LESSER_THAN_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN);
					}
					else {
						query.append(WHERE_LESSER_THAN);
					}
				}
			}

			query.append(ORDER_BY_CLAUSE);

			String[] orderByFields = orderByComparator.getOrderByFields();

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC_HAS_NEXT);
					}
					else {
						query.append(ORDER_BY_DESC_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC);
					}
					else {
						query.append(ORDER_BY_DESC);
					}
				}
			}
		}

		String sql = query.toString();

		Query q = session.createQuery(sql);

		q.setFirstResult(0);
		q.setMaxResults(2);

		QueryPos qPos = QueryPos.getInstance(q);

		qPos.add(agentId);

		qPos.add(state);

		if (orderByComparator != null) {
			Object[] values = orderByComparator.getOrderByConditionValues(delivery);

			for (Object value : values) {
				qPos.add(value);
			}
		}

		List<Delivery> list = q.list();

		if (list.size() == 2) {
			return list.get(1);
		}
		else {
			return null;
		}
	}

	/**
	 * Returns all the deliveries where agentId = &#63; and state = any &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param agentId the agent ID
	 * @param states the states
	 * @return the matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public List<Delivery> findByDeliveryStateAndAgentId(long agentId,
		int[] states) throws SystemException {
		return findByDeliveryStateAndAgentId(agentId, states,
			QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
	}

	/**
	 * Returns a range of all the deliveries where agentId = &#63; and state = any &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param agentId the agent ID
	 * @param states the states
	 * @param start the lower bound of the range of deliveries
	 * @param end the upper bound of the range of deliveries (not inclusive)
	 * @return the range of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public List<Delivery> findByDeliveryStateAndAgentId(long agentId,
		int[] states, int start, int end) throws SystemException {
		return findByDeliveryStateAndAgentId(agentId, states, start, end, null);
	}

	/**
	 * Returns an ordered range of all the deliveries where agentId = &#63; and state = any &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param agentId the agent ID
	 * @param states the states
	 * @param start the lower bound of the range of deliveries
	 * @param end the upper bound of the range of deliveries (not inclusive)
	 * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
	 * @return the ordered range of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public List<Delivery> findByDeliveryStateAndAgentId(long agentId,
		int[] states, int start, int end, OrderByComparator orderByComparator)
		throws SystemException {
		FinderPath finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_DELIVERYSTATEANDAGENTID;
		Object[] finderArgs = null;

		if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
				(orderByComparator == null)) {
			finderArgs = new Object[] { agentId, StringUtil.merge(states) };
		}
		else {
			finderArgs = new Object[] {
					agentId, StringUtil.merge(states),
					
					start, end, orderByComparator
				};
		}

		List<Delivery> list = (List<Delivery>)FinderCacheUtil.getResult(finderPath,
				finderArgs, this);

		if ((list != null) && !list.isEmpty()) {
			for (Delivery delivery : list) {
				if ((agentId != delivery.getAgentId()) ||
						!ArrayUtil.contains(states, delivery.getState())) {
					list = null;

					break;
				}
			}
		}

		if (list == null) {
			StringBundler query = new StringBundler();

			query.append(_SQL_SELECT_DELIVERY_WHERE);

			boolean conjunctionable = false;

			if (conjunctionable) {
				query.append(WHERE_AND);
			}

			query.append(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_AGENTID_5);

			conjunctionable = true;

			if ((states == null) || (states.length > 0)) {
				if (conjunctionable) {
					query.append(WHERE_AND);
				}

				query.append(StringPool.OPEN_PARENTHESIS);

				for (int i = 0; i < states.length; i++) {
					query.append(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_STATE_5);

					if ((i + 1) < states.length) {
						query.append(WHERE_OR);
					}
				}

				query.append(StringPool.CLOSE_PARENTHESIS);

				conjunctionable = true;
			}

			if (orderByComparator != null) {
				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(agentId);

				if (states != null) {
					qPos.add(states);
				}

				list = (List<Delivery>)QueryUtil.list(q, getDialect(), start,
						end);
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (list == null) {
					FinderCacheUtil.removeResult(finderPath, finderArgs);
				}
				else {
					cacheResult(list);

					FinderCacheUtil.putResult(finderPath, finderArgs, list);
				}

				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and agentId = &#63; or throws a {@link com.mad.bikepony.NoSuchDeliveryException} if it could not be found.
	 *
	 * @param deliveryId the delivery ID
	 * @param agentId the agent ID
	 * @return the matching delivery
	 * @throws com.mad.bikepony.NoSuchDeliveryException if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery findByDeliveryIdAndAgentId(long deliveryId, long agentId)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = fetchByDeliveryIdAndAgentId(deliveryId, agentId);

		if (delivery == null) {
			StringBundler msg = new StringBundler(6);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("deliveryId=");
			msg.append(deliveryId);

			msg.append(", agentId=");
			msg.append(agentId);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			if (_log.isWarnEnabled()) {
				_log.warn(msg.toString());
			}

			throw new NoSuchDeliveryException(msg.toString());
		}

		return delivery;
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and agentId = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache.
	 *
	 * @param deliveryId the delivery ID
	 * @param agentId the agent ID
	 * @return the matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByDeliveryIdAndAgentId(long deliveryId, long agentId)
		throws SystemException {
		return fetchByDeliveryIdAndAgentId(deliveryId, agentId, true);
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and agentId = &#63; or returns <code>null</code> if it could not be found, optionally using the finder cache.
	 *
	 * @param deliveryId the delivery ID
	 * @param agentId the agent ID
	 * @param retrieveFromCache whether to use the finder cache
	 * @return the matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByDeliveryIdAndAgentId(long deliveryId, long agentId,
		boolean retrieveFromCache) throws SystemException {
		Object[] finderArgs = new Object[] { deliveryId, agentId };

		Object result = null;

		if (retrieveFromCache) {
			result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDAGENTID,
					finderArgs, this);
		}

		if (result instanceof Delivery) {
			Delivery delivery = (Delivery)result;

			if ((deliveryId != delivery.getDeliveryId()) ||
					(agentId != delivery.getAgentId())) {
				result = null;
			}
		}

		if (result == null) {
			StringBundler query = new StringBundler(3);

			query.append(_SQL_SELECT_DELIVERY_WHERE);

			query.append(_FINDER_COLUMN_DELIVERYIDANDAGENTID_DELIVERYID_2);

			query.append(_FINDER_COLUMN_DELIVERYIDANDAGENTID_AGENTID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(deliveryId);

				qPos.add(agentId);

				List<Delivery> list = q.list();

				result = list;

				Delivery delivery = null;

				if (list.isEmpty()) {
					FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDAGENTID,
						finderArgs, list);
				}
				else {
					delivery = list.get(0);

					cacheResult(delivery);

					if ((delivery.getDeliveryId() != deliveryId) ||
							(delivery.getAgentId() != agentId)) {
						FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDAGENTID,
							finderArgs, delivery);
					}
				}

				return delivery;
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (result == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDAGENTID,
						finderArgs);
				}

				closeSession(session);
			}
		}
		else {
			if (result instanceof List<?>) {
				return null;
			}
			else {
				return (Delivery)result;
			}
		}
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and agentId = &#63; and state = &#63; or throws a {@link com.mad.bikepony.NoSuchDeliveryException} if it could not be found.
	 *
	 * @param deliveryId the delivery ID
	 * @param agentId the agent ID
	 * @param state the state
	 * @return the matching delivery
	 * @throws com.mad.bikepony.NoSuchDeliveryException if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery findByDeliveryIdAndDeliveryStateAndAgentId(
		long deliveryId, long agentId, int state)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = fetchByDeliveryIdAndDeliveryStateAndAgentId(deliveryId,
				agentId, state);

		if (delivery == null) {
			StringBundler msg = new StringBundler(8);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("deliveryId=");
			msg.append(deliveryId);

			msg.append(", agentId=");
			msg.append(agentId);

			msg.append(", state=");
			msg.append(state);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			if (_log.isWarnEnabled()) {
				_log.warn(msg.toString());
			}

			throw new NoSuchDeliveryException(msg.toString());
		}

		return delivery;
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and agentId = &#63; and state = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache.
	 *
	 * @param deliveryId the delivery ID
	 * @param agentId the agent ID
	 * @param state the state
	 * @return the matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByDeliveryIdAndDeliveryStateAndAgentId(
		long deliveryId, long agentId, int state) throws SystemException {
		return fetchByDeliveryIdAndDeliveryStateAndAgentId(deliveryId, agentId,
			state, true);
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and agentId = &#63; and state = &#63; or returns <code>null</code> if it could not be found, optionally using the finder cache.
	 *
	 * @param deliveryId the delivery ID
	 * @param agentId the agent ID
	 * @param state the state
	 * @param retrieveFromCache whether to use the finder cache
	 * @return the matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByDeliveryIdAndDeliveryStateAndAgentId(
		long deliveryId, long agentId, int state, boolean retrieveFromCache)
		throws SystemException {
		Object[] finderArgs = new Object[] { deliveryId, agentId, state };

		Object result = null;

		if (retrieveFromCache) {
			result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
					finderArgs, this);
		}

		if (result instanceof Delivery) {
			Delivery delivery = (Delivery)result;

			if ((deliveryId != delivery.getDeliveryId()) ||
					(agentId != delivery.getAgentId()) ||
					(state != delivery.getState())) {
				result = null;
			}
		}

		if (result == null) {
			StringBundler query = new StringBundler(4);

			query.append(_SQL_SELECT_DELIVERY_WHERE);

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_DELIVERYID_2);

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_AGENTID_2);

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_STATE_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(deliveryId);

				qPos.add(agentId);

				qPos.add(state);

				List<Delivery> list = q.list();

				result = list;

				Delivery delivery = null;

				if (list.isEmpty()) {
					FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
						finderArgs, list);
				}
				else {
					delivery = list.get(0);

					cacheResult(delivery);

					if ((delivery.getDeliveryId() != deliveryId) ||
							(delivery.getAgentId() != agentId) ||
							(delivery.getState() != state)) {
						FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
							finderArgs, delivery);
					}
				}

				return delivery;
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (result == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
						finderArgs);
				}

				closeSession(session);
			}
		}
		else {
			if (result instanceof List<?>) {
				return null;
			}
			else {
				return (Delivery)result;
			}
		}
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and trackingCode = &#63; and agentId = &#63; or throws a {@link com.mad.bikepony.NoSuchDeliveryException} if it could not be found.
	 *
	 * @param deliveryId the delivery ID
	 * @param trackingCode the tracking code
	 * @param agentId the agent ID
	 * @return the matching delivery
	 * @throws com.mad.bikepony.NoSuchDeliveryException if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery findByDeliveryIdAndTrackingCodeAndAgentId(long deliveryId,
		String trackingCode, long agentId)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = fetchByDeliveryIdAndTrackingCodeAndAgentId(deliveryId,
				trackingCode, agentId);

		if (delivery == null) {
			StringBundler msg = new StringBundler(8);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("deliveryId=");
			msg.append(deliveryId);

			msg.append(", trackingCode=");
			msg.append(trackingCode);

			msg.append(", agentId=");
			msg.append(agentId);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			if (_log.isWarnEnabled()) {
				_log.warn(msg.toString());
			}

			throw new NoSuchDeliveryException(msg.toString());
		}

		return delivery;
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and trackingCode = &#63; and agentId = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache.
	 *
	 * @param deliveryId the delivery ID
	 * @param trackingCode the tracking code
	 * @param agentId the agent ID
	 * @return the matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByDeliveryIdAndTrackingCodeAndAgentId(
		long deliveryId, String trackingCode, long agentId)
		throws SystemException {
		return fetchByDeliveryIdAndTrackingCodeAndAgentId(deliveryId,
			trackingCode, agentId, true);
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and trackingCode = &#63; and agentId = &#63; or returns <code>null</code> if it could not be found, optionally using the finder cache.
	 *
	 * @param deliveryId the delivery ID
	 * @param trackingCode the tracking code
	 * @param agentId the agent ID
	 * @param retrieveFromCache whether to use the finder cache
	 * @return the matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByDeliveryIdAndTrackingCodeAndAgentId(
		long deliveryId, String trackingCode, long agentId,
		boolean retrieveFromCache) throws SystemException {
		Object[] finderArgs = new Object[] { deliveryId, trackingCode, agentId };

		Object result = null;

		if (retrieveFromCache) {
			result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
					finderArgs, this);
		}

		if (result instanceof Delivery) {
			Delivery delivery = (Delivery)result;

			if ((deliveryId != delivery.getDeliveryId()) ||
					!Validator.equals(trackingCode, delivery.getTrackingCode()) ||
					(agentId != delivery.getAgentId())) {
				result = null;
			}
		}

		if (result == null) {
			StringBundler query = new StringBundler(4);

			query.append(_SQL_SELECT_DELIVERY_WHERE);

			query.append(_FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_DELIVERYID_2);

			if (trackingCode == null) {
				query.append(_FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_TRACKINGCODE_1);
			}
			else {
				if (trackingCode.equals(StringPool.BLANK)) {
					query.append(_FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_TRACKINGCODE_3);
				}
				else {
					query.append(_FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_TRACKINGCODE_2);
				}
			}

			query.append(_FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_AGENTID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(deliveryId);

				if (trackingCode != null) {
					qPos.add(trackingCode);
				}

				qPos.add(agentId);

				List<Delivery> list = q.list();

				result = list;

				Delivery delivery = null;

				if (list.isEmpty()) {
					FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
						finderArgs, list);
				}
				else {
					delivery = list.get(0);

					cacheResult(delivery);

					if ((delivery.getDeliveryId() != deliveryId) ||
							(delivery.getTrackingCode() == null) ||
							!delivery.getTrackingCode().equals(trackingCode) ||
							(delivery.getAgentId() != agentId)) {
						FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
							finderArgs, delivery);
					}
				}

				return delivery;
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (result == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
						finderArgs);
				}

				closeSession(session);
			}
		}
		else {
			if (result instanceof List<?>) {
				return null;
			}
			else {
				return (Delivery)result;
			}
		}
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and deliveryCode = &#63; and agentId = &#63; or throws a {@link com.mad.bikepony.NoSuchDeliveryException} if it could not be found.
	 *
	 * @param deliveryId the delivery ID
	 * @param deliveryCode the delivery code
	 * @param agentId the agent ID
	 * @return the matching delivery
	 * @throws com.mad.bikepony.NoSuchDeliveryException if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery findByDeliveryIdAndDeliveryCodeAndAgentId(long deliveryId,
		String deliveryCode, long agentId)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = fetchByDeliveryIdAndDeliveryCodeAndAgentId(deliveryId,
				deliveryCode, agentId);

		if (delivery == null) {
			StringBundler msg = new StringBundler(8);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("deliveryId=");
			msg.append(deliveryId);

			msg.append(", deliveryCode=");
			msg.append(deliveryCode);

			msg.append(", agentId=");
			msg.append(agentId);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			if (_log.isWarnEnabled()) {
				_log.warn(msg.toString());
			}

			throw new NoSuchDeliveryException(msg.toString());
		}

		return delivery;
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and deliveryCode = &#63; and agentId = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache.
	 *
	 * @param deliveryId the delivery ID
	 * @param deliveryCode the delivery code
	 * @param agentId the agent ID
	 * @return the matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByDeliveryIdAndDeliveryCodeAndAgentId(
		long deliveryId, String deliveryCode, long agentId)
		throws SystemException {
		return fetchByDeliveryIdAndDeliveryCodeAndAgentId(deliveryId,
			deliveryCode, agentId, true);
	}

	/**
	 * Returns the delivery where deliveryId = &#63; and deliveryCode = &#63; and agentId = &#63; or returns <code>null</code> if it could not be found, optionally using the finder cache.
	 *
	 * @param deliveryId the delivery ID
	 * @param deliveryCode the delivery code
	 * @param agentId the agent ID
	 * @param retrieveFromCache whether to use the finder cache
	 * @return the matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByDeliveryIdAndDeliveryCodeAndAgentId(
		long deliveryId, String deliveryCode, long agentId,
		boolean retrieveFromCache) throws SystemException {
		Object[] finderArgs = new Object[] { deliveryId, deliveryCode, agentId };

		Object result = null;

		if (retrieveFromCache) {
			result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
					finderArgs, this);
		}

		if (result instanceof Delivery) {
			Delivery delivery = (Delivery)result;

			if ((deliveryId != delivery.getDeliveryId()) ||
					!Validator.equals(deliveryCode, delivery.getDeliveryCode()) ||
					(agentId != delivery.getAgentId())) {
				result = null;
			}
		}

		if (result == null) {
			StringBundler query = new StringBundler(4);

			query.append(_SQL_SELECT_DELIVERY_WHERE);

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYID_2);

			if (deliveryCode == null) {
				query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYCODE_1);
			}
			else {
				if (deliveryCode.equals(StringPool.BLANK)) {
					query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYCODE_3);
				}
				else {
					query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYCODE_2);
				}
			}

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_AGENTID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(deliveryId);

				if (deliveryCode != null) {
					qPos.add(deliveryCode);
				}

				qPos.add(agentId);

				List<Delivery> list = q.list();

				result = list;

				Delivery delivery = null;

				if (list.isEmpty()) {
					FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
						finderArgs, list);
				}
				else {
					delivery = list.get(0);

					cacheResult(delivery);

					if ((delivery.getDeliveryId() != deliveryId) ||
							(delivery.getDeliveryCode() == null) ||
							!delivery.getDeliveryCode().equals(deliveryCode) ||
							(delivery.getAgentId() != agentId)) {
						FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
							finderArgs, delivery);
					}
				}

				return delivery;
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (result == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
						finderArgs);
				}

				closeSession(session);
			}
		}
		else {
			if (result instanceof List<?>) {
				return null;
			}
			else {
				return (Delivery)result;
			}
		}
	}

	/**
	 * Returns the delivery where trackingCode = &#63; or throws a {@link com.mad.bikepony.NoSuchDeliveryException} if it could not be found.
	 *
	 * @param trackingCode the tracking code
	 * @return the matching delivery
	 * @throws com.mad.bikepony.NoSuchDeliveryException if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery findByTrackingCode(String trackingCode)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = fetchByTrackingCode(trackingCode);

		if (delivery == null) {
			StringBundler msg = new StringBundler(4);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("trackingCode=");
			msg.append(trackingCode);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			if (_log.isWarnEnabled()) {
				_log.warn(msg.toString());
			}

			throw new NoSuchDeliveryException(msg.toString());
		}

		return delivery;
	}

	/**
	 * Returns the delivery where trackingCode = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache.
	 *
	 * @param trackingCode the tracking code
	 * @return the matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByTrackingCode(String trackingCode)
		throws SystemException {
		return fetchByTrackingCode(trackingCode, true);
	}

	/**
	 * Returns the delivery where trackingCode = &#63; or returns <code>null</code> if it could not be found, optionally using the finder cache.
	 *
	 * @param trackingCode the tracking code
	 * @param retrieveFromCache whether to use the finder cache
	 * @return the matching delivery, or <code>null</code> if a matching delivery could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery fetchByTrackingCode(String trackingCode,
		boolean retrieveFromCache) throws SystemException {
		Object[] finderArgs = new Object[] { trackingCode };

		Object result = null;

		if (retrieveFromCache) {
			result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_TRACKINGCODE,
					finderArgs, this);
		}

		if (result instanceof Delivery) {
			Delivery delivery = (Delivery)result;

			if (!Validator.equals(trackingCode, delivery.getTrackingCode())) {
				result = null;
			}
		}

		if (result == null) {
			StringBundler query = new StringBundler(2);

			query.append(_SQL_SELECT_DELIVERY_WHERE);

			if (trackingCode == null) {
				query.append(_FINDER_COLUMN_TRACKINGCODE_TRACKINGCODE_1);
			}
			else {
				if (trackingCode.equals(StringPool.BLANK)) {
					query.append(_FINDER_COLUMN_TRACKINGCODE_TRACKINGCODE_3);
				}
				else {
					query.append(_FINDER_COLUMN_TRACKINGCODE_TRACKINGCODE_2);
				}
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				if (trackingCode != null) {
					qPos.add(trackingCode);
				}

				List<Delivery> list = q.list();

				result = list;

				Delivery delivery = null;

				if (list.isEmpty()) {
					FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_TRACKINGCODE,
						finderArgs, list);
				}
				else {
					delivery = list.get(0);

					cacheResult(delivery);

					if ((delivery.getTrackingCode() == null) ||
							!delivery.getTrackingCode().equals(trackingCode)) {
						FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_TRACKINGCODE,
							finderArgs, delivery);
					}
				}

				return delivery;
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (result == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_TRACKINGCODE,
						finderArgs);
				}

				closeSession(session);
			}
		}
		else {
			if (result instanceof List<?>) {
				return null;
			}
			else {
				return (Delivery)result;
			}
		}
	}

	/**
	 * Returns all the deliveries.
	 *
	 * @return the deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public List<Delivery> findAll() throws SystemException {
		return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
	}

	/**
	 * Returns a range of all the deliveries.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param start the lower bound of the range of deliveries
	 * @param end the upper bound of the range of deliveries (not inclusive)
	 * @return the range of deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public List<Delivery> findAll(int start, int end) throws SystemException {
		return findAll(start, end, null);
	}

	/**
	 * Returns an ordered range of all the deliveries.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param start the lower bound of the range of deliveries
	 * @param end the upper bound of the range of deliveries (not inclusive)
	 * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
	 * @return the ordered range of deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public List<Delivery> findAll(int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		FinderPath finderPath = null;
		Object[] finderArgs = new Object[] { start, end, orderByComparator };

		if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
				(orderByComparator == null)) {
			finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL;
			finderArgs = FINDER_ARGS_EMPTY;
		}
		else {
			finderPath = FINDER_PATH_WITH_PAGINATION_FIND_ALL;
			finderArgs = new Object[] { start, end, orderByComparator };
		}

		List<Delivery> list = (List<Delivery>)FinderCacheUtil.getResult(finderPath,
				finderArgs, this);

		if (list == null) {
			StringBundler query = null;
			String sql = null;

			if (orderByComparator != null) {
				query = new StringBundler(2 +
						(orderByComparator.getOrderByFields().length * 3));

				query.append(_SQL_SELECT_DELIVERY);

				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);

				sql = query.toString();
			}
			else {
				sql = _SQL_SELECT_DELIVERY;
			}

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				if (orderByComparator == null) {
					list = (List<Delivery>)QueryUtil.list(q, getDialect(),
							start, end, false);

					Collections.sort(list);
				}
				else {
					list = (List<Delivery>)QueryUtil.list(q, getDialect(),
							start, end);
				}
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (list == null) {
					FinderCacheUtil.removeResult(finderPath, finderArgs);
				}
				else {
					cacheResult(list);

					FinderCacheUtil.putResult(finderPath, finderArgs, list);
				}

				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Removes all the deliveries where agentId = &#63; and state = &#63; from the database.
	 *
	 * @param agentId the agent ID
	 * @param state the state
	 * @throws SystemException if a system exception occurred
	 */
	public void removeByDeliveryStateAndAgentId(long agentId, int state)
		throws SystemException {
		for (Delivery delivery : findByDeliveryStateAndAgentId(agentId, state)) {
			remove(delivery);
		}
	}

	/**
	 * Removes the delivery where deliveryId = &#63; and agentId = &#63; from the database.
	 *
	 * @param deliveryId the delivery ID
	 * @param agentId the agent ID
	 * @return the delivery that was removed
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery removeByDeliveryIdAndAgentId(long deliveryId, long agentId)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = findByDeliveryIdAndAgentId(deliveryId, agentId);

		return remove(delivery);
	}

	/**
	 * Removes the delivery where deliveryId = &#63; and agentId = &#63; and state = &#63; from the database.
	 *
	 * @param deliveryId the delivery ID
	 * @param agentId the agent ID
	 * @param state the state
	 * @return the delivery that was removed
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery removeByDeliveryIdAndDeliveryStateAndAgentId(
		long deliveryId, long agentId, int state)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = findByDeliveryIdAndDeliveryStateAndAgentId(deliveryId,
				agentId, state);

		return remove(delivery);
	}

	/**
	 * Removes the delivery where deliveryId = &#63; and trackingCode = &#63; and agentId = &#63; from the database.
	 *
	 * @param deliveryId the delivery ID
	 * @param trackingCode the tracking code
	 * @param agentId the agent ID
	 * @return the delivery that was removed
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery removeByDeliveryIdAndTrackingCodeAndAgentId(
		long deliveryId, String trackingCode, long agentId)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = findByDeliveryIdAndTrackingCodeAndAgentId(deliveryId,
				trackingCode, agentId);

		return remove(delivery);
	}

	/**
	 * Removes the delivery where deliveryId = &#63; and deliveryCode = &#63; and agentId = &#63; from the database.
	 *
	 * @param deliveryId the delivery ID
	 * @param deliveryCode the delivery code
	 * @param agentId the agent ID
	 * @return the delivery that was removed
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery removeByDeliveryIdAndDeliveryCodeAndAgentId(
		long deliveryId, String deliveryCode, long agentId)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = findByDeliveryIdAndDeliveryCodeAndAgentId(deliveryId,
				deliveryCode, agentId);

		return remove(delivery);
	}

	/**
	 * Removes the delivery where trackingCode = &#63; from the database.
	 *
	 * @param trackingCode the tracking code
	 * @return the delivery that was removed
	 * @throws SystemException if a system exception occurred
	 */
	public Delivery removeByTrackingCode(String trackingCode)
		throws NoSuchDeliveryException, SystemException {
		Delivery delivery = findByTrackingCode(trackingCode);

		return remove(delivery);
	}

	/**
	 * Removes all the deliveries from the database.
	 *
	 * @throws SystemException if a system exception occurred
	 */
	public void removeAll() throws SystemException {
		for (Delivery delivery : findAll()) {
			remove(delivery);
		}
	}

	/**
	 * Returns the number of deliveries where agentId = &#63; and state = &#63;.
	 *
	 * @param agentId the agent ID
	 * @param state the state
	 * @return the number of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public int countByDeliveryStateAndAgentId(long agentId, int state)
		throws SystemException {
		Object[] finderArgs = new Object[] { agentId, state };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_DELIVERYSTATEANDAGENTID,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(3);

			query.append(_SQL_COUNT_DELIVERY_WHERE);

			query.append(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_AGENTID_2);

			query.append(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_STATE_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(agentId);

				qPos.add(state);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_DELIVERYSTATEANDAGENTID,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Returns the number of deliveries where agentId = &#63; and state = any &#63;.
	 *
	 * @param agentId the agent ID
	 * @param states the states
	 * @return the number of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public int countByDeliveryStateAndAgentId(long agentId, int[] states)
		throws SystemException {
		Object[] finderArgs = new Object[] { agentId, StringUtil.merge(states) };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_WITH_PAGINATION_COUNT_BY_DELIVERYSTATEANDAGENTID,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler();

			query.append(_SQL_COUNT_DELIVERY_WHERE);

			boolean conjunctionable = false;

			if (conjunctionable) {
				query.append(WHERE_AND);
			}

			query.append(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_AGENTID_5);

			conjunctionable = true;

			if ((states == null) || (states.length > 0)) {
				if (conjunctionable) {
					query.append(WHERE_AND);
				}

				query.append(StringPool.OPEN_PARENTHESIS);

				for (int i = 0; i < states.length; i++) {
					query.append(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_STATE_5);

					if ((i + 1) < states.length) {
						query.append(WHERE_OR);
					}
				}

				query.append(StringPool.CLOSE_PARENTHESIS);

				conjunctionable = true;
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(agentId);

				if (states != null) {
					qPos.add(states);
				}

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_WITH_PAGINATION_COUNT_BY_DELIVERYSTATEANDAGENTID,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Returns the number of deliveries where deliveryId = &#63; and agentId = &#63;.
	 *
	 * @param deliveryId the delivery ID
	 * @param agentId the agent ID
	 * @return the number of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public int countByDeliveryIdAndAgentId(long deliveryId, long agentId)
		throws SystemException {
		Object[] finderArgs = new Object[] { deliveryId, agentId };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDAGENTID,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(3);

			query.append(_SQL_COUNT_DELIVERY_WHERE);

			query.append(_FINDER_COLUMN_DELIVERYIDANDAGENTID_DELIVERYID_2);

			query.append(_FINDER_COLUMN_DELIVERYIDANDAGENTID_AGENTID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(deliveryId);

				qPos.add(agentId);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDAGENTID,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Returns the number of deliveries where deliveryId = &#63; and agentId = &#63; and state = &#63;.
	 *
	 * @param deliveryId the delivery ID
	 * @param agentId the agent ID
	 * @param state the state
	 * @return the number of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public int countByDeliveryIdAndDeliveryStateAndAgentId(long deliveryId,
		long agentId, int state) throws SystemException {
		Object[] finderArgs = new Object[] { deliveryId, agentId, state };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(4);

			query.append(_SQL_COUNT_DELIVERY_WHERE);

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_DELIVERYID_2);

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_AGENTID_2);

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_STATE_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(deliveryId);

				qPos.add(agentId);

				qPos.add(state);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Returns the number of deliveries where deliveryId = &#63; and agentId = &#63; and state = any &#63;.
	 *
	 * @param deliveryId the delivery ID
	 * @param agentId the agent ID
	 * @param states the states
	 * @return the number of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public int countByDeliveryIdAndDeliveryStateAndAgentId(long deliveryId,
		long agentId, int[] states) throws SystemException {
		Object[] finderArgs = new Object[] {
				deliveryId, agentId, StringUtil.merge(states)
			};

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_WITH_PAGINATION_COUNT_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler();

			query.append(_SQL_COUNT_DELIVERY_WHERE);

			boolean conjunctionable = false;

			if (conjunctionable) {
				query.append(WHERE_AND);
			}

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_DELIVERYID_5);

			conjunctionable = true;

			if (conjunctionable) {
				query.append(WHERE_AND);
			}

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_AGENTID_5);

			conjunctionable = true;

			if ((states == null) || (states.length > 0)) {
				if (conjunctionable) {
					query.append(WHERE_AND);
				}

				query.append(StringPool.OPEN_PARENTHESIS);

				for (int i = 0; i < states.length; i++) {
					query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_STATE_5);

					if ((i + 1) < states.length) {
						query.append(WHERE_OR);
					}
				}

				query.append(StringPool.CLOSE_PARENTHESIS);

				conjunctionable = true;
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(deliveryId);

				qPos.add(agentId);

				if (states != null) {
					qPos.add(states);
				}

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_WITH_PAGINATION_COUNT_BY_DELIVERYIDANDDELIVERYSTATEANDAGENTID,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Returns the number of deliveries where deliveryId = &#63; and trackingCode = &#63; and agentId = &#63;.
	 *
	 * @param deliveryId the delivery ID
	 * @param trackingCode the tracking code
	 * @param agentId the agent ID
	 * @return the number of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public int countByDeliveryIdAndTrackingCodeAndAgentId(long deliveryId,
		String trackingCode, long agentId) throws SystemException {
		Object[] finderArgs = new Object[] { deliveryId, trackingCode, agentId };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(4);

			query.append(_SQL_COUNT_DELIVERY_WHERE);

			query.append(_FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_DELIVERYID_2);

			if (trackingCode == null) {
				query.append(_FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_TRACKINGCODE_1);
			}
			else {
				if (trackingCode.equals(StringPool.BLANK)) {
					query.append(_FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_TRACKINGCODE_3);
				}
				else {
					query.append(_FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_TRACKINGCODE_2);
				}
			}

			query.append(_FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_AGENTID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(deliveryId);

				if (trackingCode != null) {
					qPos.add(trackingCode);
				}

				qPos.add(agentId);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDTRACKINGCODEANDAGENTID,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Returns the number of deliveries where deliveryId = &#63; and deliveryCode = &#63; and agentId = &#63;.
	 *
	 * @param deliveryId the delivery ID
	 * @param deliveryCode the delivery code
	 * @param agentId the agent ID
	 * @return the number of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public int countByDeliveryIdAndDeliveryCodeAndAgentId(long deliveryId,
		String deliveryCode, long agentId) throws SystemException {
		Object[] finderArgs = new Object[] { deliveryId, deliveryCode, agentId };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(4);

			query.append(_SQL_COUNT_DELIVERY_WHERE);

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYID_2);

			if (deliveryCode == null) {
				query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYCODE_1);
			}
			else {
				if (deliveryCode.equals(StringPool.BLANK)) {
					query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYCODE_3);
				}
				else {
					query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYCODE_2);
				}
			}

			query.append(_FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_AGENTID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(deliveryId);

				if (deliveryCode != null) {
					qPos.add(deliveryCode);
				}

				qPos.add(agentId);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_DELIVERYIDANDDELIVERYCODEANDAGENTID,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Returns the number of deliveries where trackingCode = &#63;.
	 *
	 * @param trackingCode the tracking code
	 * @return the number of matching deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public int countByTrackingCode(String trackingCode)
		throws SystemException {
		Object[] finderArgs = new Object[] { trackingCode };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_TRACKINGCODE,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(2);

			query.append(_SQL_COUNT_DELIVERY_WHERE);

			if (trackingCode == null) {
				query.append(_FINDER_COLUMN_TRACKINGCODE_TRACKINGCODE_1);
			}
			else {
				if (trackingCode.equals(StringPool.BLANK)) {
					query.append(_FINDER_COLUMN_TRACKINGCODE_TRACKINGCODE_3);
				}
				else {
					query.append(_FINDER_COLUMN_TRACKINGCODE_TRACKINGCODE_2);
				}
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				if (trackingCode != null) {
					qPos.add(trackingCode);
				}

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_TRACKINGCODE,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Returns the number of deliveries.
	 *
	 * @return the number of deliveries
	 * @throws SystemException if a system exception occurred
	 */
	public int countAll() throws SystemException {
		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
				FINDER_ARGS_EMPTY, this);

		if (count == null) {
			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(_SQL_COUNT_DELIVERY);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL,
					FINDER_ARGS_EMPTY, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Initializes the delivery persistence.
	 */
	public void afterPropertiesSet() {
		String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
					com.liferay.util.service.ServiceProps.get(
						"value.object.listener.com.mad.bikepony.model.Delivery")));

		if (listenerClassNames.length > 0) {
			try {
				List<ModelListener<Delivery>> listenersList = new ArrayList<ModelListener<Delivery>>();

				for (String listenerClassName : listenerClassNames) {
					listenersList.add((ModelListener<Delivery>)InstanceFactory.newInstance(
							listenerClassName));
				}

				listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
			}
			catch (Exception e) {
				_log.error(e);
			}
		}
	}

	public void destroy() {
		EntityCacheUtil.removeCache(DeliveryImpl.class.getName());
		FinderCacheUtil.removeCache(FINDER_CLASS_NAME_ENTITY);
		FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
	}

	@BeanReference(type = AgentPersistence.class)
	protected AgentPersistence agentPersistence;
	@BeanReference(type = DeliveryPersistence.class)
	protected DeliveryPersistence deliveryPersistence;
	@BeanReference(type = QuestionPersistence.class)
	protected QuestionPersistence questionPersistence;
	@BeanReference(type = QuestionResponsePersistence.class)
	protected QuestionResponsePersistence questionResponsePersistence;
	@BeanReference(type = ResourcePersistence.class)
	protected ResourcePersistence resourcePersistence;
	@BeanReference(type = UserPersistence.class)
	protected UserPersistence userPersistence;
	private static final String _SQL_SELECT_DELIVERY = "SELECT delivery FROM Delivery delivery";
	private static final String _SQL_SELECT_DELIVERY_WHERE = "SELECT delivery FROM Delivery delivery WHERE ";
	private static final String _SQL_COUNT_DELIVERY = "SELECT COUNT(delivery) FROM Delivery delivery";
	private static final String _SQL_COUNT_DELIVERY_WHERE = "SELECT COUNT(delivery) FROM Delivery delivery WHERE ";
	private static final String _FINDER_COLUMN_DELIVERYSTATEANDAGENTID_AGENTID_2 =
		"delivery.agentId = ? AND ";
	private static final String _FINDER_COLUMN_DELIVERYSTATEANDAGENTID_AGENTID_5 =
		"(" +
		_removeConjunction(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_AGENTID_2) +
		")";
	private static final String _FINDER_COLUMN_DELIVERYSTATEANDAGENTID_STATE_2 = "delivery.state = ?";
	private static final String _FINDER_COLUMN_DELIVERYSTATEANDAGENTID_STATE_5 = "(" +
		_removeConjunction(_FINDER_COLUMN_DELIVERYSTATEANDAGENTID_STATE_2) +
		")";
	private static final String _FINDER_COLUMN_DELIVERYIDANDAGENTID_DELIVERYID_2 =
		"delivery.deliveryId = ? AND ";
	private static final String _FINDER_COLUMN_DELIVERYIDANDAGENTID_AGENTID_2 = "delivery.agentId = ?";
	private static final String _FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_DELIVERYID_2 =
		"delivery.deliveryId = ? AND ";
	private static final String _FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_DELIVERYID_5 =
		"(" +
		_removeConjunction(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_DELIVERYID_2) +
		")";
	private static final String _FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_AGENTID_2 =
		"delivery.agentId = ? AND ";
	private static final String _FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_AGENTID_5 =
		"(" +
		_removeConjunction(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_AGENTID_2) +
		")";
	private static final String _FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_STATE_2 =
		"delivery.state = ?";
	private static final String _FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_STATE_5 =
		"(" +
		_removeConjunction(_FINDER_COLUMN_DELIVERYIDANDDELIVERYSTATEANDAGENTID_STATE_2) +
		")";
	private static final String _FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_DELIVERYID_2 =
		"delivery.deliveryId = ? AND ";
	private static final String _FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_TRACKINGCODE_1 =
		"delivery.trackingCode IS NULL AND ";
	private static final String _FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_TRACKINGCODE_2 =
		"delivery.trackingCode = ? AND ";
	private static final String _FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_TRACKINGCODE_3 =
		"(delivery.trackingCode IS NULL OR delivery.trackingCode = ?) AND ";
	private static final String _FINDER_COLUMN_DELIVERYIDANDTRACKINGCODEANDAGENTID_AGENTID_2 =
		"delivery.agentId = ?";
	private static final String _FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYID_2 =
		"delivery.deliveryId = ? AND ";
	private static final String _FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYCODE_1 =
		"delivery.deliveryCode IS NULL AND ";
	private static final String _FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYCODE_2 =
		"delivery.deliveryCode = ? AND ";
	private static final String _FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_DELIVERYCODE_3 =
		"(delivery.deliveryCode IS NULL OR delivery.deliveryCode = ?) AND ";
	private static final String _FINDER_COLUMN_DELIVERYIDANDDELIVERYCODEANDAGENTID_AGENTID_2 =
		"delivery.agentId = ?";
	private static final String _FINDER_COLUMN_TRACKINGCODE_TRACKINGCODE_1 = "delivery.trackingCode IS NULL";
	private static final String _FINDER_COLUMN_TRACKINGCODE_TRACKINGCODE_2 = "delivery.trackingCode = ?";
	private static final String _FINDER_COLUMN_TRACKINGCODE_TRACKINGCODE_3 = "(delivery.trackingCode IS NULL OR delivery.trackingCode = ?)";

	private static String _removeConjunction(String sql) {
		int pos = sql.indexOf(" AND ");

		if (pos != -1) {
			sql = sql.substring(0, pos);
		}

		return sql;
	}

	private static final String _ORDER_BY_ENTITY_ALIAS = "delivery.";
	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Delivery exists with the primary key ";
	private static final String _NO_SUCH_ENTITY_WITH_KEY = "No Delivery exists with the key {";
	private static final boolean _HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE = GetterUtil.getBoolean(PropsUtil.get(
				PropsKeys.HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE));
	private static Log _log = LogFactoryUtil.getLog(DeliveryPersistenceImpl.class);
	private static Delivery _nullDelivery = new DeliveryImpl() {
			@Override
			public Object clone() {
				return this;
			}

			@Override
			public CacheModel<Delivery> toCacheModel() {
				return _nullDeliveryCacheModel;
			}
		};

	private static CacheModel<Delivery> _nullDeliveryCacheModel = new CacheModel<Delivery>() {
			public Delivery toEntityModel() {
				return _nullDelivery;
			}
		};
}